<template>
  <div class="coach-management-container">
    <!-- 成功提示对话框 -->
    <el-dialog v-model="successDialogVisible" :show-close="false" width="400px" center align="center" class="success-dialog">
      <div class="success-content">
        <div class="success-icon">
          <el-icon :size="60" color="#67C23A"><Check /></el-icon>
        </div>
        <h2 class="success-title">保存成功</h2>
        <p class="success-desc">{{ countDown }}秒后回到数据管理页面</p>
        <el-button plain @click="handleSuccessClose">返回</el-button>
      </div>
    </el-dialog>
    <div class="page-header">
      <div class="left">
        <h2>教练管理系统</h2>
      </div>
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索教练..."
          clearable
          class="search-input"
        >
          <template #prefix>
            <el-icon><SearchIcon /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="showAddCoachDialog">
          <el-icon><Plus /></el-icon>添加教练
        </el-button>
      </div>
    </div>

    <div class="filter-section">
      <div class="filter-item">
        <span>状态：</span>
        <el-select v-model="statusFilter" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="在职" value="在职" />
          <el-option label="离职" value="离职" />
        </el-select>
      </div>
      <div class="filter-item">
        <span>科目：</span>
        <el-select v-model="subjectFilter" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="科目一" value="科目一" />
          <el-option label="科目二" value="科目二" />
          <el-option label="科目三" value="科目三" />
          <el-option label="科目四" value="科目四" />
        </el-select>
      </div>
      <div class="filter-item">
        <el-dropdown @command="handleMoreFilter">
          <span class="el-dropdown-link">
            <el-icon><Setting /></el-icon> 更多筛选
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="experience">按经验排序</el-dropdown-item>
              <el-dropdown-item command="rating">按评分排序</el-dropdown-item>
              <el-dropdown-item command="students">按学员数排序</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <el-table
      :data="paginatedCoaches"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column label="教练姓名" min-width="120">
        <template #default="scope">
          <div class="coach-info">
            <el-avatar :size="40" icon="UserFilled" />
            <span>{{ scope.row.coachName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="coachId" label="教练编号" width="80" />
      <el-table-column prop="coachPhone" label="联系电话" min-width="120" />
      <el-table-column prop="affiliatedDrivingSchool" label="所属驾校" min-width="120" />
      <el-table-column prop="atiin" label="教练资质" width="100" />
      <el-table-column prop="courseId" label="课程编号" width="80" />
      <el-table-column label="操作" min-width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleEdit(scope.row)"
            :icon="EditIcon"
            circle
          />
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            :icon="DeleteIcon"
            circle
          />
          <el-button
            size="small"
            type="info"
            @click="viewStudents(scope.row)"
            :icon="ViewIcon"
            circle
          />
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCoaches"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑教练对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑教练信息' : '添加教练信息'"
      width="50%"
      :before-close="handleDialogClose"
    >
      <div style="padding: 0 20%">
        <el-form
          ref="coachFormRef"
          :model="coachForm"
          :rules="coachRules"
          label-width="120px"
          class="coach-form"
        >
          <el-form-item label="姓名" prop="coachName" label-width="80px">
            <el-input v-model="coachForm.coachName" placeholder="请输入教练姓名" />
          </el-form-item>
          
          <el-form-item label="电话" prop="coachPhone" label-width="80px">
            <el-input v-model="coachForm.coachPhone" placeholder="请输入联系电话" />
          </el-form-item>
          
          <el-form-item label="所属驾校" prop="affiliatedDrivingSchool" label-width="80px">
            <el-input v-model="coachForm.affiliatedDrivingSchool" placeholder="请输入所属驾校" />
          </el-form-item>
          
          <el-form-item label="资质" prop="atiin" label-width="80px">
            <el-input v-model="coachForm.atiin" placeholder="请输入教练资质" />
          </el-form-item>
          
          <el-form-item>
            <div style="display: flex; justify-content: center; gap: 20px;">
              <el-button type="primary" @click="submitCoachForm">保存</el-button>
              <el-button @click="dialogVisible = false">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 查看学员对话框 -->
    <el-dialog v-model="studentsDialogVisible" title="教练的学员列表" width="800px">
      <el-table :data="coachStudents" style="width: 100%" border>
        <el-table-column prop="studentName" label="学员姓名" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="phone" label="联系电话" />
        <el-table-column prop="enrollDate" label="报名日期" />
        <el-table-column prop="subject" label="当前科目" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStudentStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Search, Plus, Edit, Delete, View, Setting, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCoachList, getCoachById, addCoach, updateCoach, deleteCoach, getStudentsByCoachId } from '../api/coach'

export default {
  name: 'EpCoachManagement',
  components: {
    Setting
  },
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalCoaches = ref(0)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const subjectFilter = ref('')
    const selectedCoach = ref(null)
    const studentsDialogVisible = ref(false)
    const coachStudents = ref([])
    const coachFormRef = ref(null)
    
    // 成功对话框相关状态
    const successDialogVisible = ref(false)
    const countDown = ref(3) // 倒计时秒数
    let countDownTimer = null
    
    // 图标引用
    const EditIcon = Edit
    const DeleteIcon = Delete
    const ViewIcon = View
    const PlusIcon = Plus
    const SearchIcon = Search
    
    // 获取教练列表
    const fetchCoaches = async () => {
      try {
        loading.value = true
        const res = await getCoachList()
        if (res.code === 200) {
          coaches.value = res.data
          totalCoaches.value = res.data.length
        } else {
          ElMessage.error(res.message || '获取教练列表失败')
        }
      } catch (error) {
        console.error('获取教练列表异常:', error)
        ElMessage.error('获取教练列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 根据ID获取教练
    const fetchCoachById = async (id) => {
      try {
        loading.value = true
        const res = await getCoachById(id)
        if (res.code === 200) {
          return res.data
        } else {
          ElMessage.error(res.message || '获取教练信息失败')
          return null
        }
      } catch (error) {
        console.error('获取教练信息异常:', error)
        ElMessage.error('获取教练信息失败')
        return null
      } finally {
        loading.value = false
      }
    }
    
    // 获取教练的学员列表
    const fetchStudentsByCoachId = async (id) => {
      try {
        loading.value = true
        const res = await getStudentsByCoachId(id)
        if (res.code === 200) {
          coachStudents.value = res.data
        } else {
          ElMessage.error(res.message || '获取学员列表失败')
        }
      } catch (error) {
        console.error('获取学员列表异常:', error)
        ElMessage.error('获取学员列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 教练数据
    const coaches = ref([])
    
    // 添加教练
    const handleAddCoach = async () => {
      if (!coachFormRef.value) return
      
      await coachFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const res = await addCoach(coachForm)
            if (res.code === 200) {
              // 关闭表单对话框
              dialogVisible.value = false
              // 重新加载教练列表
              fetchCoaches()
              // 显示成功提示对话框
              showSuccessDialog()
            } else {
              ElMessage.error(res.message || '添加教练失败')
            }
          } catch (error) {
            console.error('添加教练异常:', error)
            ElMessage.error('添加教练失败')
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    // 显示成功对话框
    const showSuccessDialog = () => {
      successDialogVisible.value = true
      countDown.value = 3
      
      // 开始倒计时
      if (countDownTimer) {
        clearInterval(countDownTimer)
      }
      
      countDownTimer = setInterval(() => {
        if (countDown.value > 0) {
          countDown.value--
        } else {
          handleSuccessClose()
        }
      }, 1000)
    }
    
    // 关闭成功对话框
    const handleSuccessClose = () => {
      successDialogVisible.value = false
      if (countDownTimer) {
        clearInterval(countDownTimer)
        countDownTimer = null
      }
    }
    
    // 更新教练
    const handleUpdateCoach = async () => {
      if (!coachFormRef.value) return
      
      await coachFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            loading.value = true
            const res = await updateCoach(coachForm.coachId, coachForm)
            if (res.code === 200) {
              // 关闭表单对话框
              dialogVisible.value = false
              // 重新加载教练列表
              fetchCoaches()
              // 显示成功提示对话框
              showSuccessDialog()
            } else {
              ElMessage.error(res.message || '更新教练失败')
            }
          } catch (error) {
            console.error('更新教练异常:', error)
            ElMessage.error('更新教练失败')
          } finally {
            loading.value = false
          }
        }
      })
    }
    
    // 删除教练
    const handleDeleteCoach = async (id) => {
      try {
        await ElMessageBox.confirm('确定要删除该教练吗？删除后无法恢复！', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        loading.value = true
        const res = await deleteCoach(id)
        if (res.code === 200) {
          ElMessage.success('删除教练成功')
          fetchCoaches() // 重新加载教练列表
        } else {
          ElMessage.error(res.message || '删除教练失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除教练异常:', error)
          ElMessage.error('删除教练失败')
        }
      } finally {
        loading.value = false
      }
    }
    
    // 查看教练的学员
    const handleViewStudents = async (coach) => {
      selectedCoach.value = coach
      studentsDialogVisible.value = true
      await fetchStudentsByCoachId(coach.coachId)
    }
    
    // 打开添加教练对话框
    const openAddDialog = () => {
      isEdit.value = false
      dialogVisible.value = true
      // 重置表单，只处理保留的字段
      coachForm.coachId = null
      coachForm.coachName = ''
      coachForm.coachPhone = ''
      coachForm.affiliatedDrivingSchool = ''
      coachForm.atiin = ''
      
      // 等待DOM更新后重置表单校验
      setTimeout(() => {
        coachFormRef.value && coachFormRef.value.resetFields()
      })
    }
    
    // 打开编辑教练对话框
    const openEditDialog = async (coach) => {
      isEdit.value = true
      dialogVisible.value = true
      
      // 获取最新教练数据
      const coachData = await fetchCoachById(coach.coachId) || coach
      
      // 填充表单数据 - 只处理保留的字段
      coachForm.coachId = coachData.coachId || null
      coachForm.coachName = coachData.coachName || ''
      coachForm.coachPhone = coachData.coachPhone || ''
      coachForm.affiliatedDrivingSchool = coachData.affiliatedDrivingSchool || ''
      coachForm.atiin = coachData.atiin || ''
      
      // 等待DOM更新后重置表单校验
      setTimeout(() => {
        coachFormRef.value && coachFormRef.value.clearValidate()
      })
    }
    
    // 处理提交表单
    const handleSubmitForm = () => {
      if (isEdit.value) {
        handleUpdateCoach()
      } else {
        handleAddCoach()
      }
    }
    
    // 页面初始化
    onMounted(() => {
      fetchCoaches()
    })
    
    // 模拟学员数据
    const studentsData = [
      { studentName: '张三', age: 22, phone: '13900139001', enrollDate: '2025-04-15', subject: '科目一', status: '学习中' },
      { studentName: '李四', age: 25, phone: '13900139002', enrollDate: '2025-04-10', subject: '科目二', status: '已通过' },
      { studentName: '王五', age: 30, phone: '13900139003', enrollDate: '2025-04-05', subject: '科目三', status: '学习中' },
      { studentName: '赵六', age: 28, phone: '13900139004', enrollDate: '2025-04-01', subject: '科目二', status: '未通过' },
      { studentName: '小一', age: 24, phone: '13181579079', enrollDate: '2025-05-01', subject: '科目一', status: '学习中' }
    ]
    
    // 表单初始化 - 只保留可直接填写的字段
    const coachForm = reactive({
      coachId: null, // 编辑时需要
      coachName: '',
      coachPhone: '',
      affiliatedDrivingSchool: '',
      atiin: ''
    })
    
    // 表单验证规则
    const coachRules = {
      coachName: [
        { required: true, message: '请输入教练姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      coachPhone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
      ],
      affiliatedDrivingSchool: [
        { required: true, message: '请输入所属驾校', trigger: 'blur' }
      ],
      atiin: [
        { required: true, message: '请输入教练资质', trigger: 'blur' }
      ]
    }
    
    // 计算总教练数量
    const computeTotalCoaches = () => {
      let result = coaches.value
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(coach => 
          coach.coachName.toLowerCase().includes(query) || 
          coach.phone.includes(query) ||
          coach.school.toLowerCase().includes(query)
        )
      }
      
      // 状态过滤
      if (statusFilter.value) {
        result = result.filter(coach => coach.status === statusFilter.value)
      }
      
      // 科目过滤
      if (subjectFilter.value) {
        result = result.filter(coach => coach.subject === subjectFilter.value)
      }
      
      return result.length
    }
    
    // 过滤后的教练列表
    const filteredCoaches = computed(() => {
      let result = coaches.value
      
      // 搜索过滤
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        result = result.filter(coach => 
          (coach.coachName?.toLowerCase().includes(query)) || 
          (coach.coachPhone?.includes(query)) ||
          (coach.affiliatedDrivingSchool?.toLowerCase().includes(query))
        )
      }
      
      // 暂时注释掉状态和科目过滤，因为后端数据模型中没有这些字段
      // 如果需要这些过滤功能，需要后端添加相应字段
      /* 
      // 状态过滤
      if (statusFilter.value) {
        result = result.filter(coach => coach.status === statusFilter.value)
      }
      
      // 科目过滤
      if (subjectFilter.value) {
        result = result.filter(coach => coach.subject === subjectFilter.value)
      }
      */
      
      return result
    })
    
    // 计算总数
    const totalFilteredCoaches = computed(() => {
      return filteredCoaches.value.length
    })
    
    // 更新totalCoaches值
    watch(totalFilteredCoaches, (newValue) => {
      totalCoaches.value = newValue
    })
    
    // 分页后的教练列表
    const paginatedCoaches = computed(() => {
      // 应用分页
      const startIndex = (currentPage.value - 1) * pageSize.value
      return filteredCoaches.value.slice(startIndex, startIndex + pageSize.value)
    })
    
    // 获取学员状态类型（用于标签颜色）
    const getStudentStatusType = (status) => {
      switch (status) {
        case '学习中': return 'primary'
        case '已通过': return 'success'
        case '未通过': return 'danger'
        default: return 'info'
      }
    }
    
    // 处理添加教练
    const showAddCoachDialog = () => {
      isEdit.value = false
      resetCoachForm()
      dialogVisible.value = true
    }
    
    // 编辑教练
    const handleEdit = (coach) => {
      isEdit.value = true
      // 复制数据到表单
      Object.keys(coachForm).forEach(key => {
        if (key === 'students') {
          // 如果该教练有学生数据则设置相应的复选框
          if (coach.students) {
            Object.keys(coachForm.students).forEach(student => {
              coachForm.students[student] = coach.students[student] || false
            })
          } else {
            // 模拟数据，随机选择一些学生
            Object.keys(coachForm.students).forEach(student => {
              coachForm.students[student] = Math.random() > 0.7
            })
          }
        } else if (coach[key] !== undefined) {
          coachForm[key] = coach[key]
        }
      })
      
      // 新增字段处理
      if (!coach.idCard) coachForm.idCard = '1101' + Math.floor(10000000000000 + Math.random() * 90000000000000)
      if (!coach.email) coachForm.email = `${coachForm.coachName}${Math.floor(100 + Math.random() * 900)}@example.com`
      
      dialogVisible.value = true
    }
    
    // 处理删除教练
    const handleDelete = (coach) => {
      ElMessageBox.confirm(
        `确定要删除教练 ${coach.coachName} 吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        // 模拟删除操作
        const index = coaches.value.findIndex(item => item.id === coach.id)
        if (index !== -1) {
          coaches.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    // 查看教练的学员
    const viewStudents = (selectedCoach) => {
      // 模拟获取该教练的学员
      loading.value = true
      console.log(`获取${selectedCoach.coachName}的学员数据`)
      setTimeout(() => {
        // 随机选择2-4名学员作为该教练的学员
        const count = Math.floor(Math.random() * 3) + 2
        coachStudents.value = studentsData.slice(0, count)
        studentsDialogVisible.value = true
        loading.value = false
      }, 500)
    }
    
    // 提交教练表单
    const submitCoachForm = async () => {
      if (!coachFormRef.value) return
      
      try {
        // 验证表单
        await coachFormRef.value.validate()
        
        // 调用对应的提交函数
        if (isEdit.value) {
          await handleUpdateCoach()
        } else {
          await handleAddCoach()
        }
      } catch (error) {
        console.error('表单验证失败', error)
        ElMessage.error('表单验证失败')
      }
    }
    
    // 处理对话框关闭
    const handleDialogClose = (done) => {
      ElMessageBox.confirm('确定要关闭吗?未保存的数据将丢失')
        .then(() => {
          done()
        })
        .catch(() => {
          // 取消关闭
        })
    }
    
    // 重置表单
    const resetCoachForm = () => {
      if (coachFormRef.value) {
        coachFormRef.value.resetFields()
      }
      coachForm.id = null
      coachForm.coachName = ''
      coachForm.age = 30
      coachForm.phone = ''
      coachForm.subject = ''
      coachForm.experience = 5
      coachForm.status = '在职'
      coachForm.school = ''
      coachForm.qualification = '中级教练'
    }
    
    // 处理更多筛选
    const handleMoreFilter = (command) => {
      if (command === 'experience') {
        coaches.value.sort((a, b) => b.experience - a.experience)
        ElMessage.success('已按驾龄/经验排序')
      } else if (command === 'rating') {
        const ratingMap = {
          '初级教练': 1,
          '中级教练': 2,
          '高级教练': 3,
          '金牌教练': 4
        }
        coaches.value.sort((a, b) => ratingMap[b.qualification] - ratingMap[a.qualification])
        ElMessage.success('已按评分排序')
      } else if (command === 'students') {
        // 模拟按学员数排序，实际应该从后端获取
        coaches.value.sort(() => Math.random() - 0.5)
        ElMessage.success('已按学员数排序')
      }
    }
    
    // 分页处理
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    
    // 监听过滤条件变化，更新总数
    watch([searchQuery, statusFilter, subjectFilter], () => {
      totalCoaches.value = computeTotalCoaches()
    })
    
    // 模拟获取教练数据
    onMounted(() => {
      loading.value = true
      // 模拟API请求延迟
      setTimeout(() => {
        totalCoaches.value = computeTotalCoaches()
        loading.value = false
      }, 500)
    })
  
  return {
    // 状态
    coachForm,
    coachRules,
    loading,
    coaches,
    dialogVisible,
    isEdit,
    currentPage,
    pageSize,
    totalCoaches,
    searchQuery,
    statusFilter,
    subjectFilter,
    selectedCoach,
    studentsDialogVisible,
    coachStudents,
    coachFormRef,
    filteredCoaches,
    paginatedCoaches,
    totalFilteredCoaches,
    // 成功提示对话框相关
    successDialogVisible,
    countDown,
    
    // 图标
    Edit: EditIcon,
    Delete: DeleteIcon,
    View: ViewIcon,
    Setting,
    Plus: PlusIcon,
    Search: SearchIcon,
    Check,
    
    // 方法
    fetchCoaches,
    fetchCoachById,
    fetchStudentsByCoachId,
    handleAddCoach,
    handleUpdateCoach,
    handleDeleteCoach,
    handleViewStudents,
    openAddDialog,
    openEditDialog,
    handleSubmitForm,
    showAddCoachDialog,
    handleEdit,
    handleDelete,
    viewStudents,
    submitCoachForm,
    handleMoreFilter,
    handleSizeChange,
    handleDialogClose,
    handleCurrentChange,
    getStudentStatusType,
    resetCoachForm,
    showSuccessDialog,
    handleSuccessClose
    }
  }
}
</script>

<style scoped>
/* 成功提示对话框样式 */
.success-dialog :deep(.el-dialog__header) {
  display: none;
}

.success-dialog :deep(.el-dialog__body) {
  padding: 30px 20px;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.success-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.success-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 10px 0;
}

.success-desc {
  font-size: 14px;
  color: #909399;
  margin: 0 0 20px 0;
}

.coach-management-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
  margin-right: 15px;
}

.filter-section {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.filter-item span {
  margin-right: 8px;
}

.coach-info {
  display: flex;
  align-items: center;
}

.coach-info span {
  margin-left: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-dropdown-link .el-icon {
  margin-right: 5px;
}
</style>
